package com.gm.wholesale.module.order.ui.needOrder;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseui.baseactivity.BaseActivity;
import com.gm.commonlib.filters.RegexConstant;
import com.gm.commonlib.filters.RegexResultFilter;
import com.gm.commonlib.module.image.ImageUtil;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.permission.PermissionUtil;
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback;
import com.gm.commonlib.views.dialog.loadingDialog.LoadingDialog;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.BuildConfig;
import com.gm.wholesale.R;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.order.bean.needorder.AddReceipBean;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderBean;
import com.gm.wholesale.module.order.bean.needorder.NeedOrderDetailBean;
import com.gm.wholesale.module.order.model.NeedOrderModel;
import com.gm.wholesale.module.order.orderStatus.NeedOrderStatusType;
import com.gm.wholesale.module.tenxunQcloud.TenxunUploadUtil;
import com.gm.wholesale.module.tenxunQcloud.bean.UploadImageBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class ReceiptActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 1;
    private EditText inputDataEd;
    private ImageView image1;
    private ImageView addImage1;
    private ImageView image2;
    private ImageView image3;
    private ImageView image4;
    private TextView cancleTv;
    private TextView submitTv;
    private ImageView closeImage1;
    private ImageView closeImage2;
    private ImageView closeImage3;
    private ImageView closeImage4;

    private LinearLayout uploadingView;

    private ArrayList<String> mImages = new ArrayList<>();
    private ArrayList<ImageView> mImageViews = new ArrayList<>();
    private ArrayList<ImageView> mCloseImageViews = new ArrayList<>();

    private List<UploadImageBean> mUpLoadImages = new ArrayList<>();

    private NeedOrderDetailBean mData;
    private NeedOrderBean needOrderBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receipt);
        mData = (NeedOrderDetailBean) getIntent().getSerializableExtra("data");
        needOrderBean = (NeedOrderBean) getIntent().getSerializableExtra("data2");
        initView();

    }


    private void initView() {
        inputDataEd = findViewById(R.id.inputDataEd);
        uploadingView = findViewById(R.id.uploadingView);
        inputDataEd.setFilters(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_72)});
        image1 = findViewById(R.id.image1);
        addImage1 = findViewById(R.id.addImage1);
        image2 = findViewById(R.id.image2);
        image3 = findViewById(R.id.image3);
        image4 = findViewById(R.id.image4);
        cancleTv = findViewById(R.id.cancleTv);
        submitTv = findViewById(R.id.submitTv);
        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);
        image4.setOnClickListener(this);
        mImageViews.add(image1);
        mImageViews.add(image2);
        mImageViews.add(image3);
        mImageViews.add(image4);
        cancleTv.setOnClickListener(this);
        submitTv.setOnClickListener(this);
        closeImage1 = findViewById(R.id.closeImage1);
        closeImage2 = findViewById(R.id.closeImage2);
        closeImage3 = findViewById(R.id.closeImage3);
        closeImage4 = findViewById(R.id.closeImage4);
        mCloseImageViews.add(closeImage1);
        mCloseImageViews.add(closeImage2);
        mCloseImageViews.add(closeImage3);
        mCloseImageViews.add(closeImage4);
        closeImage1.setOnClickListener(this);
        closeImage2.setOnClickListener(this);
        closeImage3.setOnClickListener(this);
        closeImage4.setOnClickListener(this);
        showDefaultView();
    }

    private void showDefaultView() {
        NeedOrderDetailBean.ReceiptBean receiptBean = mData.getReceipt();
        if (receiptBean != null &&
                !TextUtils.isEmpty(receiptBean.getAmount()) &&
                Double.parseDouble(receiptBean.getAmount()) > 0) {
            inputDataEd.setText(receiptBean.getAmount());
        }
        List<String> images = receiptBean.getImages();
        if (images != null) {
            for (String image : images) {
                UploadImageBean uploadImageBean = new UploadImageBean();
                if (!image.startsWith("http")) {
                    image = BuildConfig.img_path + image;
                }
                uploadImageBean.setLocalImage(image);
                uploadImageBean.setUploadImage(image);
                mUpLoadImages.add(uploadImageBean);
            }
            showView();
        }
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.cancleTv) {
            finish();
            return;
        }
        if (viewId == R.id.submitTv) { //提交回执
            subMit();
            return;
        }
        if (viewId == R.id.closeImage1) {
            updateView(image1);
            return;
        }
        if (viewId == R.id.closeImage2) {
            updateView(image2);
            return;
        }
        if (viewId == R.id.closeImage3) {
            updateView(image3);
            return;
        }
        if (viewId == R.id.closeImage4) {
            updateView(image4);
            return;
        }
        choiceImage();
    }

    private void subMit() {
        String money = inputDataEd.getText().toString();
        AddReceipBean addReceipBean = new AddReceipBean();
        addReceipBean.setVersion(mData.getVersion());
        AddReceipBean.ReceiptBean receiptBean = new AddReceipBean.ReceiptBean();
        if (mUpLoadImages != null && !mUpLoadImages.isEmpty()) {
            List<String> images = new ArrayList<>();
            for (UploadImageBean uploadImageBean : mUpLoadImages) {
                String uploadImage = uploadImageBean.getUploadImage();
                if (uploadImage == null) continue;
                if (uploadImage.startsWith("http")) {
                    images.add(uploadImage);
                } else {
                    images.add(BuildConfig.img_path + uploadImageBean.getUploadImage());
                }
            }
            receiptBean.setImages(images);
        }
        receiptBean.setAmount(money);
        addReceipBean.setReceipt(receiptBean);

        NeedOrderModel.addReceipt(mData.getNeedsID(), this, addReceipBean, new BaseHttpObserver<BaseResp>() {
            @Override
            protected void handleResultOkResp(BaseResp resp) {
                ToastUtil.showToast("回执成功");
                needOrderBean.setStatus(NeedOrderStatusType.YWC.getType());
                EvenBusUtil.updateNeedOrderByReceipt(needOrderBean);
                finish();
            }
        });
    }

    private void updateView(ImageView imageView) {
        if (imageView.getTag() != null) {
            mUpLoadImages.remove(imageView.getTag());
        }
        imageView.setTag(null);
        for (ImageView imageView1 : mImageViews) {
            imageView1.setImageResource(0);
        }
        for (ImageView closeImage : mCloseImageViews) {
            closeImage.setVisibility(View.GONE);
        }
        showView();
    }

    private void choiceImage() {
                    ImageUtil.clearnImage();
                    //不限数量的多选
                    ImageSelector.builder()
                            .useCamera(true) // 设置是否使用拍照
                            .setSingle(false)  //设置是否单选
                            .setMaxSelectCount(4 - mUpLoadImages.size()) // 图片的最大选择数量，小于等于0时，不限数量。
                            // .setSelected(mImages) // 把已选的图片传入默认选中。
                            .canPreview(false) //是否可以预览图片，默认为true
                            .start(ReceiptActivity.this, REQUEST_CODE); // 打开相册

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            if (mImages != null) {
                mImages.clear();
            }
            //获取选择器返回的数据
            mImages = data.getStringArrayListExtra(
                    ImageSelector.SELECT_RESULT);
            uploadImages();
        }
    }

    private void setBtnEnable(boolean enable) {
        submitTv.setEnabled(enable);
        cancleTv.setEnabled(enable);
        image1.setEnabled(enable);
    }

    private void uploadImages() {
        LoadingDialog.newLoadingDialog().show(getActivity());
        if (mImages != null && !mImages.isEmpty()) {
            uploadingView.setVisibility(View.VISIBLE);
            setBtnEnable(false);
            TenxunUploadUtil.uploadReceipt(context, mImages, (result, errorMsg) -> runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setBtnEnable(true);
                    uploadingView.setVisibility(View.GONE);
                    LoadingDialog.newLoadingDialog().hid();
                    if (!TextUtils.isEmpty(errorMsg)) {
                        ToastUtil.showToast(errorMsg);
                    } else {
                        mUpLoadImages.addAll(result);
                        showView();
                    }
                }
            }));
        }
    }

    private void showView() {
        ImageUtil.clearnImage();
        if (!mUpLoadImages.isEmpty()) {
            int pos = 1;
            if (mUpLoadImages.size() == 4) {
                addImage1.setVisibility(View.GONE);
                pos = 0;
            } else {
                addImage1.setVisibility(View.VISIBLE);
            }
            for (UploadImageBean uploadImageBean : mUpLoadImages) {
                if (pos >= mImageViews.size()) {
                    return;
                }
                ImageView imageView = mImageViews.get(pos);
                String imagePath = uploadImageBean.getLocalImage();
                if (TextUtils.isEmpty(imagePath)) {
                    continue;
                }
                if (imagePath.startsWith("http")) {
                    ImageUtil.showImage(imageView, uploadImageBean.getLocalImage());
                } else {
                    ImageUtil.showImageBySdcard(imageView, uploadImageBean.getLocalImage());
                }

                imageView.setTag(uploadImageBean);
                mCloseImageViews.get(pos).setVisibility(View.VISIBLE);
                pos++;
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImageUtil.clearnImage();
    }
}
